package service

import (
	"encoding/json"
	"errors"
	"github.com/guonaihong/gout"
	"net/http"
	"strconv"
	"time"
	"wwgin/global/variable"
)

//第三方接口,ip查询
type ArktIpFind struct {
	Url       string //接口的地址
	AppKey    string //app key
	AppSecret string
	AppCode   string
}

var ArkIp = ArktIpFind{
	"https://ipaddr.market.alicloudapi.com/ip_addr_search/ch/v1",
	//"http://192.168.60.249/111.php", //暂时使用本地接口模拟接口返回,正常接口有ip限制本地无法访问
	"xx",
	"xx",
	"xxx",
}

//接口正常返回的数据
/*
{"输入待检测字符串":"27.19.195.235","待查询IP地址":"27.19.195.235","发起端IP地址":"114.116.207.100","IP地址解析状态":"艾科瑞特，让企业业绩长青","IP地址解析实体信息":{"待查询IP地址解析实体信息":{"IP地址":"27.19.195.235","洲际":"亚洲","国家":"中国","国家英文名称":"CHINA","国家英文名称缩写":"CN","省份":"湖北","城市":"武汉","区域":"武昌","ISP运营商":"电信","国家行政编码":"420106","GPS":"114.31589,30.55389","IP地址解析状态":"艾科瑞特，让企业业绩长青"},"发起端IP地址解析实体信息":{"IP地址":"114.116.207.100","洲际":"亚洲","国家":"中国","国家英文名称":"CHINA","国家英文名称缩写":"CN","省份":"北京","城市":"北京","区域":"","ISP运营商":"华为云","国家行政编码":"110100","GPS":"116.405285,39.904989","IP地址解析状态":"艾科瑞特，让企业业绩长青"}}}
*/

type ArkIpInfo struct {
	IP地址解析实体信息 map[string]map[string]string
	IP地址解析状态   string
	发起端IP地址    string
	待查询IP地址    string
	输入待检测字符串   string
}

//也可以使用 init 函数读取yarm中的配置来实例化

func (a *ArktIpFind) GetInfo(ip string) (ArkIpInfo, error) {
	p := ArkIpInfo{}

	var body []byte //接收返回的数据信息
	var http_code int
	err := gout.GET(a.Url).
		SetQuery(gout.H{"IP_ADDR": ip}).
		SetHeader(gout.H{"Authorization": "APPCODE "+a.AppCode, "Content-Type": "application/json; charset=utf-8"}).
		Code(&http_code).
		BindBody(&body).
		SetTimeout(5 * time.Second).
		Do()

	variable.ZapLog.Info("request:" + ip + "|" + strconv.Itoa(http_code) + "|" + string(body))

	if err != nil {
		variable.ZapLog.Error("错误1")
		return p, errors.New("第三方接口请求失败")
	}
	if http_code != http.StatusOK {
		variable.ZapLog.Error("错误2")
		return p, errors.New("第三方接口返回错误,http状态:" + strconv.Itoa(http_code))
	}
	err = json.Unmarshal(body, &p)
	if err != nil {
		variable.ZapLog.Error("错误3")
		return p, errors.New("第三方接口数据返回的不是一个json:" + err.Error())
	}
	return p, nil
}
